<style>
#container {
  padding: 0px;
  margin: 0px;
  width: 1000px;
  height: 600px;
}</style>

<template>
  <div class="addDbs">
    <el-form ref="form" :model="form" label-width="120px">
      <el-form-item label="站长用户名：">
        <el-input v-model="form.yname" style="width: 500px" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="登录密码：">
        <el-input v-model="form.pwd" type="password" style="width: 500px" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item label="站长手机号：">
        <el-input v-model="form.tel" type="text" style="width: 500px" placeholder="请输入站长手机号"></el-input>
      </el-form-item>
      <el-form-item label="站点名称：">
        <el-input v-model="form.name" type="text" style="width: 500px" placeholder="请输入站点名称"></el-input>
      </el-form-item>
      <el-form-item label="站点所在地：">
        <el-cascader
            size="large"
            :options="pcaTextArr"
            v-model="ruleForm.locations">
        </el-cascader>
      </el-form-item>
      <el-form-item label="站点详细地址：">
        <el-input v-model="form.detailedAddress" disabled style="width: 500px"
                  placeholder="请输入站点详细地址"></el-input>
      </el-form-item>
<!--      <el-form-item label="配送时段">-->
<!--        <el-radio-group v-model="form.type">-->
<!--          <el-radio label="3">全天配送</el-radio>-->
<!--          <el-radio label="2">自定义时段</el-radio>-->
<!--        </el-radio-group>-->
<!--        <br>-->
<!--        <span v-show="form.type==2">-->
<!--          <el-time-picker-->
<!--              style="margin-left: 100px;margin-top: 10px"-->
<!--              v-model="value1"-->
<!--              :picker-options="{selectableRange: '00:00:00 - 23:59:59'}"-->
<!--              placeholder="~">-->
<!--        </el-time-picker>-->
<!--        <el-time-picker-->
<!--            v-model="value2"-->
<!--            :picker-options="{selectableRange: '00:00:00 - 23:59:59'}"-->
<!--            placeholder="~">-->
<!--        </el-time-picker><br>-->
<!--        <el-time-picker-->
<!--            style="margin-left: 100px;margin-top: 10px"-->
<!--            v-model="value3"-->
<!--            :picker-options="{selectableRange: '00:00:00 - 23:59:59'}"-->
<!--            placeholder="~">-->
<!--        </el-time-picker>-->
<!--        <el-time-picker-->
<!--            v-model="value4"-->
<!--            :picker-options="{selectableRange: '00:00:00 - 23:59:59'}"-->
<!--            placeholder="~">-->
<!--        </el-time-picker><br>-->
<!--        <el-time-picker-->
<!--            style="margin-left: 100px;margin-top: 10px"-->
<!--            v-model="value5"-->
<!--            :picker-options="{selectableRange: '00:00:00 - 23:59:59'}"-->
<!--            placeholder="~">-->
<!--        </el-time-picker>-->
<!--        <el-time-picker-->
<!--            v-model="value6"-->
<!--            :picker-options="{selectableRange: '00:00:00 - 23:59:59'}"-->
<!--            placeholder="~">-->
<!--        </el-time-picker>-->
<!--      </span>-->
<!--      </el-form-item>-->
      <el-form-item label="配送区域：">
        <div style="float: left" id="container"></div>
        <div id="my-panel" style="width: 60px;position: relative;bottom: 0px;right: 270px;float: left"></div>
        <el-button style="float: left;position: relative;right: 250px;top: 49px" @click="drawPolyline">开始绘制区域
        </el-button>
        <el-button style="float: left;position: relative;right: 230px;top: 49px" @click="clearDrawing">清除</el-button>
      </el-form-item>
    </el-form>


    <el-form :model="mh" label-width="120px" style="position: relative;bottom: 580px;left: 20px">
      <el-form-item>
        <el-autocomplete
            v-model="keywords"
            style="width: 300px"
            :fetch-suggestions="querySearchAsync"
            placeholder="请输入内容"
            @select="handleSelect"
        ></el-autocomplete>
      </el-form-item>
    </el-form>


    <el-button type="primary" @click="fanhui">返回</el-button>
    <el-button type="primary" @click="addDBS">保存</el-button>
  </div>
</template>

<script>

import AMapLoader from '@amap/amap-jsapi-loader';

import {
  provinceAndCityData,
  pcTextArr,
  regionData,
  pcaTextArr,
  codeToText,
} from "element-china-area-data";

import Moment from 'moment'

import AddressParse from 'address-parse'


export default {
  data() {
    return {
      mh: {},
      name: "map-view",
      selectedLocation: [],
      form: {
        detailedAddress: ''
      },
      form2: {
        lng: 116.157102,
        lat: 40.134066,
        address: '',
      },
      value1: "",
      value2: "",
      value3: "",
      value4: "",
      value5: "",
      value6: "",
      pcaTextArr,
      selectedOptions: [],
      keywords: "",
      ruleForm: {
        locations: ["", "", ""],
      },
      geoCoder: null,
      AutoComplete: null,mouseTool: null,
      polyline: null,
      bc: false,
    }
  },

  mounted() {
    this.initAMap();
  },

  methods: {
    // 获取一个详细地址中的省份和市以及县
    extractAddressInfo(address) {

      const [result] = AddressParse.parse(address);

      return result;
    },


    // 创建地图的方法
    initAMap() {
      window._AMapSecurityConfig = {
        securityJsCode: "afe0e70ddad866eaa6b9a74b4f32d9e6",
      };
      AMapLoader.load({
        key: "18eba6b371526a0f0c79c505f1141578", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.Scale", "AMap.ToolBar", "AMap.PlaceSearch", "AMap.AutoComplete", "AMap.Geocoder", "AMap.MouseTool", "AMap.Polyline"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
      })
          .then((AMap) => {

            this.map = new AMap.Map("container", {
              // 设置地图容器id 
              // viewMode: "3D", // 是否为3D地图模式
              zoom: 17, // 初始化地图级别
              center: [parseFloat(this.form2.lng), parseFloat(this.form2.lat)], // 初始化地图中心点位置

            });
            const self = this;
            // 添加鼠标工具，用于在地图上点击获取点
            this.mouseTool = new AMap.MouseTool(this.map);

            // 绑定绘制完成事件监听器
            this.mouseTool.on('draw', (event) => {
              // console.log('覆盖物对象绘制完成');
              // 这里可根据需要对绘制完成的覆盖物对象（event.obj）进行进一步处理

              // 假设绘制完成的对象是AMap.Polyline类型，获取其路径信息（包含各个顶点坐标）
              if (event.obj instanceof AMap.Polyline) {
                const path = event.obj.getPath();

                // 将路径信息中的每个顶点坐标转换为普通的经纬度数组形式
                const coordinates = path.map(point => [point.lng, point.lat]);

                // 此时coordinates就是包含了绘制区域各个顶点经纬度的二维数组
                // 可以根据需要进一步处理这个数据，比如将其转换为字符串形式以便存储
                const regionData = JSON.stringify(coordinates);
                this.form.coordinate = regionData;

                // 计算区域的中心点坐标（这里简单取路径的第一个点和最后一个点的中点作为示例）
                const firstPoint = path[0];
                const lastPoint = path[path.length - 1];
                const centerPoint = [];
                centerPoint[0] = (firstPoint.lng + lastPoint.lng) / 2;
                centerPoint[1] = (firstPoint.lat + lastPoint.lat) / 2;

                // 使用逆地理编码服务获取地址信息
                this.geoCoder.getAddress([centerPoint[0], centerPoint[1]], (status, result) => {
                  if (status === "complete") {
                    const address = result.regeocode.formattedAddress;
                    // 假设从地址中提取街道名称作为区域名称示例
                    const regionName = address.split(' ')[0];


                    if (this.extractAddressInfo(regionName).area != this.ruleForm.locations[2]) {
                      this.$message.error('区域名称与地址信息不一致')
                      // if (this.polyline) {
                      //   this.map.remove(this.polyline);
                      // }
                      this.form.detailedAddress = regionName;
                      this.form2.lng = centerPoint[0];
                      this.form2.lat = centerPoint[1];
                      this.initAMap();
                      // this.polyline = null;
                      // 这里可以将区域名称和其他绘制区域信息一起进行后续处理，比如存储到数据库
                      this.bc = false
                    } else {
                      // 这里可以将区域名称和其他绘制区域信息一起进行后续处理，比如存储到数据库
                      this.form.detailedAddress = regionName;
                      this.bc = true
                    }
                  } else {
                    console.log('获取地址信息失败');
                  }
                });
              }
            });

            //异步加载控件
            AMap.plugin('AMap.ToolBar', function () {
              var toolbar = new AMap.ToolBar(); //缩放工具条实例化
              self.map.addControl(toolbar); //添加控件
            });
            //异步加载控件
            AMap.plugin('AMap.Scale', function () {
              var toolbar = new AMap.Scale(); //缩放工具条实例化
              self.map.addControl(toolbar); //添加控件
            });
            self.geoCoder = new AMap.Geocoder({
              city: "010", //城市设为北京，默认：“全国”
              radius: 1000, //范围，默认：500
            });
            // AMap.plugin(["AMap.PlaceSearch"], function () {
            //   const placeSearch = new AMap.PlaceSearch({
            //     pageSize: 5, //单页显示结果条数
            //     pageIndex: 1, //页码
            //     city: "010", //兴趣点城市
            //     citylimit: true, //是否强制限制在设置的城市内搜索
            //     map: self.map, //展现结果的地图实例
            //     panel: "my-panel", //参数值为你页面定义容器的 id 值<div id="my-panel"></div>，结果列表将在此容器中进行展示。
            //     autoFitView: true, //是否自动调整地图视野使绘制的 Marker 点都处于视口的可见范围
            //   });
            //   // 监听用户输入变化来触发查询
            //   placeSearch.search("北京大学"); //使用插件搜索关键字并查看结果
            // });
          })
          .catch((e) => {
            console.log(e);
          });
    },

    drawPolyline() {
      if (this.mouseTool) {
        this.polyline = this.mouseTool.polyline({
          strokeColor: "#3366FF",
          strokeOpacity: 1,
          strokeWeight: 6,
          strokeStyle: "solid"
        });
      }
    },

    // 清除方法
    clearDrawing() {

        this.initAMap()
    },
    handleSelect(val) {
      if (!val) {
        return;
      }
      this.form2 = {
        lng: val.location.lng,
        lat: val.location.lat,
      };
      this.removeMarker();
      this.setMapMarker();
    },


    setMapMarker() {
      this.map.setFitView();
      this.marker = new AMap.Marker({
        map: this.map,
        position: [this.form2.lng, this.form2.lat],
      });
      this.toGeoCoder();
      this.map.setFitView();
      this.map.add(this.marker);
    },
    removeMarker() {
      if (this.marker) {
        this.map.remove(this.marker);
      }
    },
    toGeoCoder() {
      let lnglat = [this.form2.lng, this.form2.lat];
      this.geoCoder.getAddress(lnglat, (status, result) => {
        if (status === "complete") {
          this.form2.address = result.regeocode.formattedAddress;
        } else {
          this.form2.address = '';
        }
      });
    },


    querySearchAsync(queryString, cb) {
      if (queryString) {
        // this.ruleForm.locations = this.ruleForm.locations.toString();
        // this.ruleForm.locations = this.ruleForm.locations.replace(/,/g, '');
        AMap.plugin(["AMap.Autocomplete"], () => {
          const autoOptions = {
            city: this.ruleForm.locations,
            input: queryString,
          };
          const autoComplete = new AMap.Autocomplete(autoOptions);
          autoComplete.search(queryString, (status, result) => {
            if (status === "complete" && result.tips) {
              this.options = result.tips.map((tip) => ({
                value: tip.name,
                location: tip.location,
              }));
            } else {
              this.options = [];
            }
            cb(this.options);
          });
        });
      } else {
        this.options = [];
        cb(this.options);
      }
    },


    // 返回方法
    fanhui() {
      this.$router.push('/dbs');
    },


      //   保存方法
    addDBS() {
      if(this.bc){
        if(this.ruleForm.locations.length!=0){
          this.form.address=this.ruleForm.locations[0]+this.ruleForm.locations[1]+this.ruleForm.locations[2];
          this.axios.post(`http://localhost:8000/xm-client/xm-distributionstations/addDbs`,this.form).then(res=>{
            if(res.data.code==200){
              this.$message.success('添加成功');
              this.$router.push('/dbs');
            }else{
              this.$message.error('添加失败');
            }
          })
        }
      }else{
        this.$message.error('请选择配送区域地址错误');
      }
    },


    showRegionOnMap(coordinate) {
      const path = [];
      coordinate.forEach(point => {
        path.push(new AMap.LngLat(point[0], point[1]));  // 将经纬度数据转换为LngLat对象添加到路径数组中
      });
      const polygon = new AMap.Polygon({
        path: path,
        strokeColor: "#3366FF",  // 多边形边框颜色
        strokeWeight: 2,  // 多边形边框宽度
        strokeOpacity: 1,  // 多边形边框透明度
        fillColor: "#CCFFFF",  // 多边形填充颜色
        fillOpacity: 0.3  // 多边形填充透明度
      });
      this.map.add(polygon);  // 将绘制的多边形添加到地图上显示
    }

  },


  created() {
    if(this.$route.query.id){
      this.axios.get(`http://localhost:8000/xm-client/xm-distributionstations/findById?id=${this.$route.query.id}`).then(res=>{
        this.form=res.data.data;
        if(res.data.data.coordinate!=null){
          this.form.coordinate=JSON.parse(res.data.data.coordinate);
          var coordinate = this.form.coordinate;
          this.showRegionOnMap(coordinate);
          // this.form2.lng=coordinate[0][0];
          // this.form2.lat=coordinate[0][1];
        }

      })
    }
    this.showRegionOnMap()
  }

}
</script>